<template>
  <div id="topicManagePage">
    <!-- 搜索表单 -->
    <a-form layout="inline" :model="searchParams" @finish="doSearch" class="search-form">
      <a-form-item label="话题标题">
        <a-input v-model:value="searchParams.title" placeholder="输入话题标题" />
      </a-form-item>
      <a-form-item label="管理员ID">
        <a-input v-model:value="searchParams.adminId" placeholder="输入管理员ID" />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit">搜索</a-button>
      </a-form-item>
      <!-- 新增按钮 -->
      <a-form-item>
        <a-button type="primary" @click="openAddModal">新增</a-button>
      </a-form-item>
    </a-form>

    <!-- 数据表格 -->
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="doTableChange"
      class="topic-table"
    >
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.dataIndex === 'serialNumber'">
          {{ (searchParams.current - 1) * searchParams.pageSize + index + 1 }}
        </template>
        <template v-else-if="column.dataIndex === 'createTime'">
          {{ dayjs(record[column.dataIndex]).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.key === 'action'">
          <a-button size="small" @click="openEditModal(record)">编辑</a-button>
          <a-button danger size="small" @click="doDelete(record.id)">删除</a-button>
        </template>
      </template>
    </a-table>

    <!-- 新增话题模态框 -->
    <a-modal
      :visible="addModalVisible"
      title="新增话题"
      okText="确认"
      cancelText="取消"
      @ok="handleAddTopic"
      @cancel="closeAddModal"
    >
      <a-form :model="addTopicForm" layout="vertical" :rules="addFormRules">
        <a-form-item label="话题标题" name="title">
          <a-input v-model:value="addTopicForm.title" placeholder="输入话题标题" />
        </a-form-item>
        <a-form-item label="管理员ID" name="adminId">
          <a-input v-model:value="addTopicForm.adminId" placeholder="输入管理员ID" />
        </a-form-item>
        <a-form-item label="话题描述" name="description">
          <a-textarea v-model:value="addTopicForm.description" placeholder="输入话题描述" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 编辑话题模态框 -->
    <a-modal
      :visible="editModalVisible"
      title="编辑话题"
      okText="确认"
      cancelText="取消"
      @ok="handleEditTopic"
      @cancel="closeEditModal"
    >
      <a-form :model="editTopicForm" layout="vertical" :rules="editFormRules">
        <a-form-item label="话题标题" name="title">
          <a-input v-model:value="editTopicForm.title" placeholder="输入话题标题" />
        </a-form-item>
        <a-form-item label="管理员ID" name="adminId">
          <a-input v-model:value="editTopicForm.adminId" placeholder="输入管理员ID" />
        </a-form-item>
        <a-form-item label="话题描述" name="description">
          <a-textarea v-model:value="editTopicForm.description" placeholder="输入话题描述" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue';
import {
  addTopicUsingPost,
  deleteTopicUsingPost,
  listTopicVoByPageUsingPost,
  updateTopicUsingPost,
} from '@/api/topicController'; // 假设这里有对应的话题管理接口
import { message } from 'ant-design-vue';
import dayjs from 'dayjs';

// 定义列
const columns = [
  {
    title: '序号',
    dataIndex: 'serialNumber',
    key: 'serialNumber',
  },
  {
    title: '话题标题',
    dataIndex: 'title',
  },
  {
    title: '管理员ID',
    dataIndex: 'adminId',
  },
  {
    title: '话题描述',
    dataIndex: 'description',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '操作',
    key: 'action',
  },
];

// 数据源
const dataList = ref([]);
const total = ref(0);

// 搜索条件
const searchParams = reactive({
  current: 1,
  pageSize: 10,
  sortField: 'createTime',
});

// 新增话题模态框相关
const addModalVisible = ref(false);
const addTopicForm = reactive({
  title: '',
  adminId: '',
  description: '',
});

// 新增表单验证规则
const addFormRules = reactive({
  title: [
    {
      required: true,
      message: '话题标题为必填项',
      trigger: 'blur',
    },
  ],
  adminId: [
    {
      required: true,
      message: '管理员ID为必填项',
      trigger: 'blur',
    },
  ],
});

// 编辑话题模态框相关
const editModalVisible = ref(false);
const editTopicForm = reactive({
  id: '',
  title: '',
  adminId: '',
  description: '',
});

// 编辑表单验证规则
const editFormRules = reactive({
  title: [
    {
      required: true,
      message: '话题标题为必填项',
      trigger: 'blur',
    },
  ],
  adminId: [
    {
      required: true,
      message: '管理员ID为必填项',
      trigger: 'blur',
    },
  ],
});

// 表格变化处理
const doTableChange = (page: any) => {
  searchParams.current = page.current;
  searchParams.pageSize = page.pageSize;
  fetchData();
};

// 分页参数
const pagination = computed(() => ({
  current: searchParams.current ?? 1,
  pageSize: searchParams.pageSize ?? 10,
  total: total.value,
  showSizeChanger: true,
  showTotal: (total) => `共 ${total} 条`,
}));

// 获取数据
const fetchData = async () => {
  const res = await listTopicVoByPageUsingPost({ ...searchParams });
  if (res.data.data) {
    dataList.value = res.data.data.records ?? [];
    total.value = res.data.data.total ?? 0;
  } else {
    message.error('获取话题数据失败');
  }
};

// 执行搜索
const doSearch = () => {
  searchParams.current = 1;
  fetchData();
};

// 删除数据
const doDelete = async (id: string) => {
  if (!id) return;
  const res = await deleteTopicUsingPost({ id });
  if (res.data.code === 0) {
    message.success('删除成功');
    fetchData();
  } else {
    message.error('删除失败');
  }
};

// 打开新增话题模态框
const openAddModal = () => {
  addModalVisible.value = true;
  // 每次打开新增模态框时清空表单数据
  addTopicForm.title = '';
  addTopicForm.adminId = '';
  addTopicForm.description = '';
};

// 关闭新增话题模态框
const closeAddModal = () => {
  addModalVisible.value = false;
};

// 处理新增话题
const handleAddTopic = async () => {
  if (addTopicForm.title && addTopicForm.adminId) {
    const res = await addTopicUsingPost({ ...addTopicForm });
    if (res.data.code === 0) {
      message.success('新增话题成功');
      closeAddModal();
      fetchData();
    } else {
      message.error('新增话题失败');
    }
  }
};

// 打开编辑话题模态框
const openEditModal = (record: any) => {
  editModalVisible.value = true;
  editTopicForm.id = record.id;
  editTopicForm.title = record.title;
  editTopicForm.adminId = record.adminId;
  editTopicForm.description = record.description;
};

// 关闭编辑话题模态框
const closeEditModal = () => {
  editModalVisible.value = false;
};

// 处理编辑话题
const handleEditTopic = async () => {
  if (editTopicForm.title && editTopicForm.adminId) {
    const res = await updateTopicUsingPost({ ...editTopicForm });
    if (res.data.code === 0) {
      message.success('编辑话题成功');
      closeEditModal();
      fetchData();
    } else {
      message.error('编辑话题失败');
    }
  }
};

onMounted(() => {
  fetchData();
});
</script>

<style scoped>
#topicManagePage {
}

.search-form {
  margin-bottom: 10px;
  display: flex;
}

.topic-table {
  margin-top: 10px;
}

.pagination {
  margin-top: 10px;
  text-align: center;
}

/* 减少表单项的间距 */
#topicManagePage :deep(.ant-form-item) {
  margin-bottom: 8px;
}

/* 减少表格单元格的内边距 */
.ant-table-tbody > tr > td {
  padding: 8px;
}

/* 减少分页组件的内边距 */
#topicManagePage :deep(.ant-pagination-options) {
  padding: 4px;
}
</style>
